<template>
  <CommonPage show-footer title="用户管理">
    <template #action>
      <div>
        <n-button type="primary" class="ml-16" @click="handleAdd">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
          新建用户
        </n-button>
      </div>
    </template>
    <n-space :wrap="false">
      <div class="tree-view-class">
        <n-input-group>
          <n-input v-model:value="treeQuery.deptNameLike" type="text" placeholder="查找部门"
                   @keypress.enter="treeHandleSearch"/>
          <n-button type="primary" @click="treeHandleSearch">
            搜索
          </n-button>
        </n-input-group>
        <n-tree
            ref="treeInstRef"
            block-line
            :data="state.deptData"
            default-expand-all
            virtual-scroll
            key-field="deptId"
            label-field="deptName"
            children-field="children"
            :on-update:selected-keys="onClickTree"
        />
      </div>

      <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :extra-params="extraParams"
          :scroll-x="1200"
          :columns="columns"
          :get-data="api.userPage"
          row-key="userId"
          @on-checked="onChecked"
          @on-data-change="(data) => (tableData = data)"
      >
        <template #queryBar>
          <QueryBarItem label="用户名称">
            <n-input
                v-model:value="queryItems.userNameLike"
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch"
            />
          </QueryBarItem>
        </template>
      </CrudTable>

    </n-space>
    <!-- 新增/编辑/查看 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        :show-footer="modalAction !== 'view'"
        @on-save="handleSave"
    >
      <n-form
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :rules="state.rules"
          :label-width="80"
          :model="modalForm"
          :disabled="modalAction === 'view'"
      >
        <n-form-item
            label="部门"
            path="deptId"
        >
          <n-tree-select
              v-model:value="modalForm.deptId"
              :options="state.deptAllOptions"
              label-field="deptName"
              key-field="deptId"
              children-field="children"
          />
        </n-form-item>
        <n-form-item
            label="头像"
            path="avatar"
        >
          <imgUpload
              :max="1"
              v-model:value="modalForm.avatar"
          />
        </n-form-item>
        <n-form-item
            label="用户名称"
            path="userName"
            :rule="{
            required: true,
            message: '请输入用户名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.userName"/>
        </n-form-item>
        <n-form-item
            label="用户昵称"
            path="nickName"
        >
          <n-input v-model:value="modalForm.nickName" placeholder="请输入用户昵称"/>
        </n-form-item>
        <n-form-item
            label="岗位"
            path="postIds"
        >
          <n-select
              v-model:value="modalForm.postIds"
              :options="state.postAllOptions"
              multiple
              label-field="postName"
              value-field="postId"
              children-field="children"
          />
        </n-form-item>
        <n-form-item
            label="角色"
            path="roleIds"
        >
          <n-select
              v-model:value="modalForm.roleIds"
              :options="state.roleAllOptions"
              multiple
              label-field="roleName"
              value-field="roleId"
              children-field="children"
          />
        </n-form-item>
        <n-form-item
            label="性别"
            path="sex"
        >
          <n-radio-group v-model:value="modalForm.sex">
            <n-space>
              <n-radio key="0" value="0">
                男
              </n-radio>
              <n-radio key="1" value="1">
                女
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item
            label="用户邮箱"
            path="email"
        >
          <n-input v-model:value="modalForm.email" placeholder="请输入用户邮箱"/>
        </n-form-item>
        <n-form-item
            label="手机号码"
            path="phonenumber"
        >
          <n-input v-model:value="modalForm.phonenumber" placeholder="请输入手机号码"/>
        </n-form-item>
        <n-form-item
            label="密码"
            path="password"
        >
          <n-input v-model:value="modalForm.password" type="password" placeholder="请输入密码"/>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="modalForm.status" checked-value="0" unchecked-value="2">
            <template #checked>
              正常
            </template>
            <template #unchecked>
              停用
            </template>
          </n-switch>
        </n-form-item>
        <n-form-item
            label="备注"
            path="remark"
        >
          <n-input
              v-model:value="modalForm.remark"
              placeholder="请输入备注"
              type="textarea"
              :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import {NButton, NSwitch} from 'naive-ui'
import {formatDateTime, renderIcon} from '@/utils'
import {useCRUD} from '@/composables'
import imgUpload from '@/components/upload/ImgUpload.vue'
import api from './api'

defineOptions({name: 'User'})

const $table = ref(null)
/** 表格数据，触发搜索的时候会更新这个值 */
const tableData = ref([])
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
/** 补充参数（可选） */
const extraParams = ref({})
/** treeQuery筛选参数（可选） */
const treeQuery = ref({})
const state = reactive({
  deptData: [],
  deptAllOptions: [],
  postAllOptions: [],
  roleAllOptions: [],
  rules: {
    // deptId: {
    //   required: true,
    //   message: '请选择部门',
    //   trigger: ['input', 'blur'],
    // },
    userName: {
      required: true,
      message: '请输入用户昵称',
      trigger: ['input', 'blur'],
    },
    sex: {
      required: true,
      message: '请选择性别',
      trigger: ['input', 'blur'],
    }
  }
})

onMounted(() => {
  $table.value?.handleSearch()
  api.deptList().then((res) => {
    state.deptData = res.result
    state.deptAllOptions = res.result
  })
  api.postPage({
    page: 1,
    pageSize: 10000
  }).then((res) => {
    state.postAllOptions = res.result.records
  })
  api.rolePage({
    page: 1,
    pageSize: 10000
  }).then((res) => {
    state.roleAllOptions = res.result.records
  })

})

const columns = [
  {type: 'selection', fixed: 'left'},
  {title: '编号', key: 'userId', width: 150, ellipsis: {tooltip: true}, resizable: true},
  {title: '用户名称', key: 'userName', width: 150, ellipsis: {tooltip: true}, resizable: true},
  {title: '用户昵称', key: 'nickName', width: 80, ellipsis: {tooltip: true}, resizable: true},
  {
    title: '创建时间',
    key: 'createTime',
    width: 150,
    resizable: true,
    render(row) {
      return h('span', formatDateTime(row['createTime']))
    },
  },
  {
    title: '最后更新时间',
    key: 'updateTime',
    width: 150,
    resizable: true,
    render(row) {
      return h('span', formatDateTime(row['updateTime']))
    },
  },
  {
    title: '状态',
    key: 'status',
    width: 60,
    resizable: true,
    align: 'center',
    fixed: 'left',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row['status'],
        checkedValue: "0",
        uncheckedValue: "2",
        onUpdateValue: (value) => handlePublish({...row, status: value}),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 240,
    resizable: true,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => handleView(row.userId),
            },
            {default: () => '查看', icon: renderIcon('majesticons:eye-line', {size: 14})}
        ),
        h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-left: 15px;',
              onClick: () => handleEdit(row.userId),
            },
            {default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', {size: 14})}
        ),

        h(
            NButton,
            {
              size: 'small',
              type: 'error',
              style: 'margin-left: 15px;',
              onClick: () => handleDelete(row.userId),
            },
            {
              default: () => '删除',
              icon: renderIcon('material-symbols:delete-outline', {size: 14}),
            }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  // if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}


const treeHandleSearch = () => {
  api.deptList(treeQuery.value).then((res) => {
    state.deptData = res.result
  })
}

const onClickTree = (treeKeys) => {
  extraParams.value.deptId = treeKeys[0]
  $table.value?.handleSearch()
}


const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  handlePublish,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '用户',
  initForm: {status: '0', deptId: 100, avatar: ''},
  doCreate: api.addUser,
  doDelete: api.deleteUser,
  doUpdate: api.updateUser,
  doGetById: api.userGetById,
  refresh: () => $table.value?.handleSearch(),
})
</script>

<style lang="scss">
.tree-view-class {
  width: 300px;
}
</style>
